<template>
  <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :before-close="cancel">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="mini">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="产品" prop="appcode">
            <el-select
              v-model="form.appcode"
              placeholder="产品"
              filterable
              clearable
              style="width: 100%">
              <el-option
                v-for="(item, index) in productListNew"
                :key="item + index"
                :label="item.name"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="渠道" prop="channel">
            <el-select v-model="form.channel" placeholder="渠道" @change="_configKeyChange(form)" filterable clearable style="width: 100%">
              <el-option
            v-for="item in dict.type.sys_channel"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="类型" prop="type">
            <el-select
              v-model="form.type"
              placeholder="类型"
              @change="_changeAppType"
              filterable
              clearable
              style="width: 100%">
              <el-option
                v-for="(item, index) in appTypeList"
                :key="item + index"
                :label="item.name"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="配置Key" prop="key">
            <el-select
              v-if="form.type === 0"
              v-model="form.key"
              @change="_configKeyChange(form)"
              placeholder="配置Key"
              filterable
              clearable
              style="width: 100%">
              <el-option
                v-for="(item, index) in dict.type.INNER_CONFIG_KEY"
                :key="item + index"
                :label="item.label"
                :value="item.value" />
            </el-select>
            <el-select
              v-if="form.type === 1"
              v-model="form.key"
              @change="_configKeyChange(form)"
              placeholder="配置Key"
              filterable
              clearable
              style="width: 100%">
              <el-option
                v-for="(item, index) in dict.type.OUT_CONFIG_KEY"
                :key="item + index"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="排序" prop="sort">
            <el-input v-model="form.sort" placeholder="请输入排序" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-query-row :label="'配置'" :labelWidth="80" style="margin-bottom:0;">
        <el-col :span="12">
          <b-code-editor v-model="form.textarea" :indent-unit="2" :height="`302px`" style="border: #C0C4CC 1px solid;" />
          <!-- <textarea v-model="form.textarea" :style="`height:302px;resize: none;`" placeholder="请输入内容" class="el-textarea__inner"></textarea> -->
        </el-col>
        <el-col :span="12">
          <b-code-editor v-model="form.jsonStr" :indent-unit="2" :height="`302px`" style="border: #C0C4CC 1px solid;" theme="duotone-light" readonly :auto-format="true" :line-wrap="true" :show-number="false"/>
        </el-col>
      </el-query-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import commonMinxis from './common'
import { saveOrUpdateConfig } from '@/api/configs/appConfig.js'
import { getAllAppList } from '@/api/configs/appConfig.js'
export default {
  dicts: ['INNER_CONFIG_KEY', 'OUT_CONFIG_KEY','sys_channel'],
  mixins: [commonMinxis],
  props: {
    title: {
      default: '新增配置',
      type: String
    },
    open: {
      default: false,
      type: Boolean
    }
  },
  data () {
    return {
      form: {
        appcode: '',
        appname: '',
        channel: '',
        type: 0,
        key: '',
        name: '',
        sort: 1,
        textarea: '',
        jsonStr: '{}'
      },
      rules: {
        appcode: [{ required: true, message: '产品不能为空', trigger: 'change' }],
        channel: [{ required: true, message: '渠道不能为空', trigger: 'change' }],
        type: [{ required: true, message: '类型不能为空', trigger: 'change' }],
        key: [{ required: true, message: '配置key不能为空', trigger: 'change' }],
        sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
      },
      productListNew: [],
      channelList: [],
      appTypeList: [{name: '应用内', value: 0} ]
    }
  },
  watch: {
    'form.textarea' (value) {
      try {
        if(JSON.parse(value.trim())) {
          this.form.jsonStr = JSON.stringify(JSON.parse(value),null,2)
        }
      } catch (e) {
        console.log(e)
        this.form.jsonStr = `{}`
      }
    }
  },
  methods: {
    submitForm () {
      let vm = this
      vm.$refs["form"].validate(valid => {
        if (valid) {
          let { textarea, jsonStr, ...params } = vm.form;
          let textareaAll= '[{"default":"1","version":"1.0.0","value":'+jsonStr+'}]';

          params.value = textareaAll.replace(/[ ]|[\r\n]/g, '');
          params.status = 1;
          saveOrUpdateConfig(params).then(response => {
            if (response.code === 200) {
              vm.$modal.msgSuccess('操作成功');
              vm._resetForm()
              vm._getProductList()
              vm.cancel()
            } else {
              vm.$modal.msgError(response.msg);
            }
          })
        }
      });
    },
    _getProductList () {
      getAllAppList().then(response => {
        this.productList = response.data.map(item => {
          return {
            name: item.appname,
            value: item.appcode,
            channelList: item.channelList
          }
        })
      })
    },
    _resetForm () {
      let vm = this;
      vm.form = {
        appcode: '',
        appname: '',
        channel: '',
        type: 0,
        key: '',
        name: '',
        sort: 1,
        textarea: '',
        jsonStr: '{}'
      };
    },
    cancel () {
      this.$emit('update:open', false)
    }
  }
}
</script>
